package com.example.yian.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.yian.entity.ProjectInfo;
import com.example.yian.mapper.ProjectInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class ProjectInfoService {

    @Autowired
    private ProjectInfoMapper projectInfoMapper;

    public ProjectInfo addOrUpdateProjectInfo(String projectName, String constructionUnit, String designUnit,
                                              String supervisionUnit, String inspectionTeamName,
                                              String inspectionPersonnel, Long userId) {
        QueryWrapper<ProjectInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        ProjectInfo projectInfo = projectInfoMapper.selectOne(queryWrapper);
        Boolean isInsert = projectInfo == null;
        if (projectInfo == null) {
            projectInfo = new ProjectInfo();
        }
        projectInfo.setUserId(userId);
        projectInfo.setProjectName(projectName);
        projectInfo.setConstructionUnit(constructionUnit);
        projectInfo.setDesignUnit(designUnit);
        projectInfo.setSupervisionUnit(supervisionUnit);
        projectInfo.setInspectionTeamName(inspectionTeamName);
        projectInfo.setInspectionPersonnel(inspectionPersonnel);
        if (isInsert) {
            projectInfoMapper.insert(projectInfo);
        } else {
            projectInfoMapper.update(projectInfo, queryWrapper);
        }
        return projectInfo;
    }

    public Optional<ProjectInfo> getProjectInfoByUserId(Long userId) {
        QueryWrapper<ProjectInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return Optional.ofNullable(projectInfoMapper.selectOne(queryWrapper));
    }
}
